package org.example.afree;

public class Merge_two_ordered_linked_lists {
    public static void main(String[] args) {

    }
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = null;
        if (list1 != null && list2!=null && list1.val <= list2.val){
            head = list1;
            list1 = list1.next;
        }else if (list1 != null && list2!=null && list1.val > list2.val) {
            head = list2;
            list2 = list2.next;
        }else if (list1 == null){
            return list2;
        }else {
            return list1;
        }
        ListNode res = head;
        while(list1 != null || list2!=null ){
            if (list1 != null && list2!=null && list1.val <= list2.val){
                ListNode node = new ListNode(list1.val);
                head.next = node;
                head = node;
                list1 = list1.next;
            }else if (list1 != null && list2!=null && list1.val > list2.val){
                ListNode node = new ListNode(list2.val);
                head.next = node;
                head = node;
                list2 = list2.next;
            }else if (list1 == null && list2!=null){
                head.next = list2;
                break;
            }else if (list1 != null && list2==null){
                head.next = list1;
                break;
            }
        }
        return res;
    }
}
